<template>
  <div class="fossilFuel">
    <div style="padding-left: 20px;">
      <el-button type="primary" icon="el-icon-plus" size="mini" @click="openDialog" style="margin-bottom: 10px;">新增</el-button>
      <el-button style="padding: 0" size="mini">
        <el-upload :limit="limitNumber" action="" accept=".xls, .xlsx" ref="uploadExcelRef"
                   :auto-upload="false" :show-file-list="false" :on-change="handleAddFun">
          <el-button size="mini" type="projectBut" icon="el-icon-upload2">上传数据</el-button>
        </el-upload>
      </el-button>
      <el-button type="warning" icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
      <el-table :data="fuelData" width="100%" border :height="tableHeight">
        <el-table-column label="名称" prop="iname" align="center"></el-table-column>
        <el-table-column label="燃料名称" prop="fuelName" align="center"></el-table-column>
        <el-table-column label="购入量(t)" prop="purchaseQuantity" align="center"></el-table-column>
        <el-table-column label="库存量(t)" prop="inventoryLevel" align="center"></el-table-column>
        <el-table-column label="低位发热量(GJ/t)" prop="lowerHeatValue" align="center"></el-table-column>
        <el-table-column label="单位热值含碳量(tC/GJ)" prop="heatCarbonContent" align="center"></el-table-column>
        <el-table-column label="燃料碳氧化率(%)" prop="carbonOxidationRate" align="center"></el-table-column>
        <el-table-column label="创建时间" prop="creationTime" align="center"></el-table-column>
        <el-table-column label="值类型" prop="valueType" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.valueType == 1?'推荐值':'实际值'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="碳排放量(tCO₂)" prop="carbonEmissions" align="center"></el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <el-button @click="handleEdit(scope.row)" size="mini">编辑</el-button>
            <el-button @click="handleDelete(scope.row)" size="mini" type="danger">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog title="新增/编辑燃料数据" :visible.sync="dialogVisible" width="30%" :append-to-body="true" @close="resetForm" custom-class="show-back-class">
      <el-form :model="fuelForm" ref="fuelForm" label-width="120px">
        <el-form-item label="名称" prop="iname">
          <el-input v-model="fuelForm.iname" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="燃料类型">
          <el-select v-model="fuelForm.fuelType" placeholder="请选择燃料类型" :disabled="true" @change="onFuelTypeChange">
            <el-option label="固体燃料" value="solid"></el-option>
            <el-option label="液体燃料" value="liquid"></el-option>
            <el-option label="气体燃料" value="gas"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="燃料名称">
          <el-select v-model="fuelForm.fuelName" placeholder="请选择燃料名称">
            <el-option v-for="fuel in fuelNameOptions[fuelForm.fuelType]" :key="fuel" :label="fuel" :value="fuel" class="index-option"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="购入量" prop="purchaseQuantity">
          <el-input v-model="fuelForm.purchaseQuantity" type="number" placeholder="请输入购入量">
            <template slot="append">10⁴Nm³</template>
          </el-input>
        </el-form-item>

        <el-form-item label="库存量" prop="inventoryLevel">
          <el-input v-model="fuelForm.inventoryLevel" type="number" placeholder="请输入库存量">
            <template slot="append">10⁴Nm³</template>
          </el-input>
        </el-form-item>

        <el-form-item label="排放因子">
          <el-input v-model="fuelForm.lowerHeatValue" type="number" placeholder="请输入排放因子" >
            <template slot="append">tCO₂/GJ</template>
          </el-input>
        </el-form-item>

        <el-form-item label="单位热值含碳量">
          <el-input v-model="fuelForm.heatCarbonContent" type="number" placeholder="请输入单位热值含碳量" >
            <template slot="append">tC/GJ</template>
          </el-input>
        </el-form-item>

        <el-form-item label="燃料碳氧化率">
          <el-input v-model="fuelForm.carbonOxidationRate" type="number" placeholder="请输入燃料碳氧化率" >
            <template slot="append">%</template>
          </el-input>
        </el-form-item>

        <el-form-item label="创建时间：" prop="creationTime">
          <el-date-picker v-model="fuelForm.creationTime" type="date" placeholder="选择日期" popper-class="show-back-class date-select-class"></el-date-picker>
        </el-form-item>
        <el-form-item label="资料文件上传">
        <el-upload class="upload-demo" :action="uploadBasecUrl" :headers="{'Authorization': Authorization }" :on-preview="handlePreview" :on-remove="handleRemove"
         :before-remove="beforeRemove" multiple :limit="5" :on-exceed="handleExceed" :on-success="upLoadSuccess" :file-list="fileList">
          <el-button size="small" type="primary">点击上传</el-button>
            <!-- <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div> -->
          </el-upload>
        </el-form-item>

        <el-form-item label="值类型">
          <el-radio-group v-model="fuelForm.valueType" >
            <el-radio v-for="dict in valueTypeOptions" :key="dict.dictValue" :label="(dict.dictValue)">
              {{dict.dictLabel}}
            </el-radio>
          </el-radio-group>
        </el-form-item>


      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSave">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  gasFuelList,
  gasFuelAdd,
  delgasFuel,
  getFossilFuelParametersList,
  gasFuelupdata,
  exportGas,
  gasChangeData,
  solidChangeData, exportSolid
} from "@/api/eleLoad/project";
import {calGasFuel} from "@/api/comput/comput";
import { getToken } from '@/utils/auth'
import * as XLSX from "xlsx";
export default {
  data() {
    return {
      uploadBasecUrl:'',
      Authorization:'',
      fileList: [],
      tableHeight: '',
      projectId: '',
      fuelData: [], // 表格数据
      dialogVisible: false, // 弹框显示状态
      limitNumber: 1,
      valueTypeOptions: [
        {dictLabel: "推荐值", dictValue: 1},
        {dictLabel: "实测值", dictValue: 2},
      ],
      fuelForm: { // 表单数据
        fuelType: 'gas',
        fuelName: '',
        purchaseQuantity: null,
        iname: null,
        inventoryLevel: null,
        lowerHeatValue: null,
        heatCarbonContent: null,
        carbonOxidationRate: null,
        carbonEmissions: null,
        valueType: 1,
        creationTime: null
      },
      fuelNameOptions: { // 不同燃料类型对应的燃料名称
        solid: ['无烟煤', '烟煤', '褐煤', '洗精煤', '其他洗煤', '其他煤制品', '焦炭'],
        liquid: ['原油', '燃料油', '汽油', '柴油'],
        gas: ['焦炉煤气', '高炉煤气', '转炉煤气', '其他煤气', '天然气']
      }
    };
  },
  created() {
    this.uploadBasecUrl = process.env.VUE_APP_BASE_API  + '/common/upload'
    this.Authorization = 'Bearer ' + getToken();
    // this.tableHeight = window.innerHeight - 200;
    this.tableHeight = 620;
    this.projectId = this.$store.state.projectDict.projectId;
    this.gasFuelList();
  },
  methods: {
    openDialog() {
      // this.resetForm();
      this.dialogVisible = true;
    },
    // 重置表单
    resetForm() {
      this.fuelForm = {
        fuelType: 'gas',
        fuelName: '',
        iname: null,
        purchaseQuantity: null,
        inventoryLevel: null,
        lowerHeatValue: null,
        heatCarbonContent: null,
        creationTime: null,
        carbonEmissions: null,
        valueType: null,
        carbonOxidationRate: null
      };
    },
    // 选择燃料类型时触发，动态获取燃料名称
    onFuelTypeChange() {
      this.fuelForm.fuelName = ''; // 清空燃料名称
      this.fetchFuelData(); // 获取低位发热量等数据
    },
    // 查询并填充燃料数据
    fetchFuelData() {
      // 根据燃料名称选择获取随机数据填充
      if (this.fuelForm.fuelName) {
        const randomValue = () => (Math.random() * 1000).toFixed(2);
        this.fuelForm.lowerHeatValue = randomValue();
        this.fuelForm.heatCarbonContent = randomValue();
        this.fuelForm.carbonOxidationRate = randomValue();
      }
    },
    // 编辑按钮点击事件
    handleEdit(row) {
      row.fuelType = 'gas'
      let fileListArr = [];
      let fileListName = [];
      this.fileList = [];
      if(row.accessoryUrl.length != 0 && row.accessoryName.length != 0) {
        fileListArr = row.accessoryUrl.split(',');
        fileListName = row.accessoryName.split(',');
        for(let i = 0; i < fileListArr.length; i++) {
          this.fileList.push({name:fileListName[i],url:fileListArr[i]})
        }
      }
      this.fuelForm = { ...row }; // 填充表单数据
      this.dialogVisible = true;
    },
    // 删除按钮点击事件
    handleDelete(row) {
      let _this = this;
      _this.$confirm('是否确认删除', { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning"
        }).then(function() {
          delgasFuel(row.id).then(response => {
            if (response.code == 200) {
              _this.$message.success('删除成功');
              _this.gasFuelList();
            } else {
              _this.$message.error(response.msg);
            }
         })
        }).catch(function() {});
    },
    getFossilFuelParametersListFun(fuelName) {
      getFossilFuelParametersList({fuelName:fuelName}).then(response => {
        this.fuelForm.lowerHeatValue = response.lowerHeatValue;
        this.fuelForm.heatCarbonContent = response.heatCarbonContent;
        this.fuelForm.carbonOxidationRate = response.carbonOxidationRate;
      })
    },
    gasFuelList() {
      gasFuelList({projectId: this.projectId}).then(response => {
        if (response.code == 200) {
          this.fuelData = response.rows;
        }
      })
    },
    // 保存按钮点击事件
    handleSave() {
      let fileListArr = [];
      let fileListName = [];
      this.fileList.map(item => {
        fileListArr.push(item.url);
        fileListName.push(item.name);
      })
      this.$refs.fuelForm.validate((valid) => {
        if (valid) {
          if(this.fuelForm.id){
            let data = {
              id: this.fuelForm.id,
              projectId: this.projectId,
              fuelName: this.fuelForm.fuelName,
              iname: this.fuelForm.iname,
              purchaseQuantity: this.fuelForm.purchaseQuantity,
              inventoryLevel: this.fuelForm.inventoryLevel,
              lowerHeatValue: this.fuelForm.lowerHeatValue,
              heatCarbonContent: this.fuelForm.heatCarbonContent,
              carbonOxidationRate: this.fuelForm.carbonOxidationRate,
              valueType: this.fuelForm.valueType,
              accessoryUrl: fileListArr.join(','),
              accessoryName: fileListName.join(','),
              creationTime: this.parseTime(this.fuelForm.creationTime, '{y}-{m}-{d}')
            }
            gasFuelupdata(data).then(response => {
              if(response.code == 200){
                this.$message.success('修改成功');
                this.fileList = [];
                this.dialogVisible = false;
                // this.gasFuelList();
                this.calCarbon();
                this.resetForm();
              } else {
                this.$message.error(response.msg);
              }
            })
          } else {
            let data = {
              fuelName: this.fuelForm.fuelName,
              iname: this.fuelForm.iname,
              projectId: this.projectId,
              purchaseQuantity: this.fuelForm.purchaseQuantity,
              inventoryLevel: this.fuelForm.inventoryLevel,
              lowerHeatValue: this.fuelForm.lowerHeatValue,
              heatCarbonContent: this.fuelForm.heatCarbonContent,
              carbonOxidationRate: this.fuelForm.carbonOxidationRate,
              valueType: this.fuelForm.valueType,
              accessoryUrl: fileListArr.join(','),
              accessoryName: fileListName.join(','),
              creationTime: this.parseTime(this.fuelForm.creationTime, '{y}-{m}-{d}')
            }
            gasFuelAdd(data).then(response => {
              if (response.code == 200) {
                this.$message.success('新增成功');
                this.fileList = [];
                this.dialogVisible = false;
                // this.gasFuelList();
                this.calCarbon();
                this.resetForm();
              } else {
                this.$message.error(response.msg);
              }
            })
          }
        } else {
          this.$message.error("请输入必有参数！");
          return false;
        }
      })
    },

    /** 选择文件上传 */
    async handleAddFun(file) {
      let that = this
      let tableList = [];
      that.regionList = [];
      that.hourData = [];
      const excel = await this.readFile(file.raw)
      let wb = XLSX.read(excel, { type: 'binary' })
      let object = {};//默认的序列
      let params = JSON.parse(JSON.stringify(XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]])));//基本信息
      console.log(params);
      // Object.assign(object,params,other);
      Object.assign(object,params);
      that.limitNumber ++;
      that.regionList.push(object);
      tableList = tableList.concat(that.fixData(that.regionList));
      //  that.emissionList = that.emissionList.concat(that.fixData(that.regionList));
      that.showList(tableList,1);
      gasChangeData({
        gasFuelList: tableList,
        projectId: that.projectId
      }).then(res => {
        if(res.code == 200) {
          this.msgSuccess("上传成功");
          that.calCarbon();
        }
      })
    },
    showList(dataList,n){
      let that =this;
      if(n*200>dataList.length){
        return
      }
      that.timeoutId =  setTimeout(function () {
        let a;
        if((n+1)*200>dataList.length){
          a = dataList.slice(n*200)
        }else {
          a = dataList.slice(n*200,(n+1)*200)
        }
        that.hourData = that.hourData.concat(a)
        n++
        that.showList(dataList,n)
      }, 1000);
    },
    // 整理表格数据
    fixData(data) {
      let tableList = [];
      let dataArr = [];
      const firstData = Array.isArray(data[0]) ? data[0] : [data[0]];
      Object.keys(firstData[0]).forEach(key => {
        if (!isNaN(key)) {  // Check if the key is a number
          dataArr.push(firstData[0][key]);
        }
      });
      for (let i = 0;i<dataArr.length;i++) {
        tableList.push({
          iname: dataArr[i]['名称'] == null ||  dataArr[i]['名称'] == undefined?dataArr[i]['名称'] = '':dataArr[i]['名称'] = dataArr[i]['名称'],
          fuelName: dataArr[i]['燃料名称'] == null ||  dataArr[i]['燃料名称'] == undefined?dataArr[i]['燃料名称'] = '':dataArr[i]['燃料名称'] = dataArr[i]['燃料名称'],
          purchaseQuantity: dataArr[i]['购入量'] == null ||  dataArr[i]['购入量'] == undefined?dataArr[i]['购入量'] = '':dataArr[i]['购入量'] = dataArr[i]['购入量'],
          inventoryLevel: dataArr[i]['库存量'] == null ||  dataArr[i]['库存量'] == undefined?dataArr[i]['库存量'] = 0:dataArr[i]['库存量'] = dataArr[i]['库存量'],
          consumption: dataArr[i]['消耗量'] == null ||  dataArr[i]['消耗量'] == undefined?dataArr[i]['消耗量'] = 0:dataArr[i]['消耗量'] = dataArr[i]['消耗量'],
          lowerHeatValue: dataArr[i]['低位发热量'] == null ||  dataArr[i]['低位发热量'] == undefined?dataArr[i]['低位发热量'] = 0:dataArr[i]['低位发热量'] = dataArr[i]['低位发热量'],
          heatCarbonContent: dataArr[i]['单位热值含碳量'] == null ||  dataArr[i]['单位热值含碳量'] == undefined?dataArr[i]['单位热值含碳量'] = 0:dataArr[i]['单位热值含碳量'] = dataArr[i]['单位热值含碳量'],
          carbonOxidationRate: dataArr[i]['燃料碳氧化率'] == null ||  dataArr[i]['燃料碳氧化率'] == undefined?dataArr[i]['燃料碳氧化率'] = 0:dataArr[i]['燃料碳氧化率'] = dataArr[i]['燃料碳氧化率'],
          creationTime: dataArr[i]['创建时间'] == null ||  dataArr[i]['创建时间'] == undefined?dataArr[i]['创建时间'] = 0:dataArr[i]['创建时间'] = dataArr[i]['创建时间'],
          valueType: dataArr[i]['值类型'] == null ||  dataArr[i]['值类型'] == undefined?dataArr[i]['值类型'] = 0:dataArr[i]['值类型'] = dataArr[i]['值类型'],
          accessoryUrl: dataArr[i]['资料文件'] == null ||  dataArr[i]['资料文件'] == undefined?dataArr[i]['资料文件'] = '':dataArr[i]['资料文件'] = dataArr[i]['资料文件'],
        })
      }
      return tableList;
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有电力排放数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportGas(queryParams);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    },

    calCarbon() {
      calGasFuel({projectId: this.projectId}).then(res => {
        if(res.code == 200) {
          // this.$message.success('计算成功');
          this.gasFuelList();
        } else {
          this.$message.error("计算失败");
        }
      })
    },
    handleRemove(file, fileList) {
      this.fileList = this.fileList.filter(item => item.name !== file.name);
    },
    handlePreview(file) {
      console.log(file);
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${ file.name }？`);
    },
    upLoadSuccess(response,file) {
      this.fileList.push({name:file.name,url:response.fileName});
    }
  },
  watch: {
    // 监听燃料名称变化，自动获取燃料数据
    'fuelForm.fuelName': function (newValue) {
      if (newValue) {
        this.getFossilFuelParametersListFun(newValue);
        // this.fetchFuelData();
      }
    }
  }
};
</script>

<style scoped>
  .fossilFuel {
    width: 100%;
    height: 100%;
  }
  .dialog-footer {
    text-align: right;
  }

  .el-table {
    height: 100%;
    width: 100%;
  }
</style>
